/*
 * @Author: jackning 270580156@qq.com
 * @Date: 2024-10-12 10:54:41
 * @LastEditors: jackning 270580156@qq.com
 * @LastEditTime: 2024-10-12 11:37:33
 * @Description: bytedesk.com https://github.com/Bytedesk/bytedesk
 *   Please be aware of the BSL license restrictions before installing Bytedesk IM – 
 *  selling, reselling, or hosting Bytedesk IM as a service is a breach of the terms and automatically terminates your rights under the license. 
 *  仅支持企业内部员工自用，严禁私自用于销售、二次销售或者部署SaaS方式销售 
 *  Business Source License 1.1: https://github.com/Bytedesk/bytedesk/blob/main/LICENSE 
 *  contact: 270580156@qq.com 
 * 联系：270580156@qq.com
 * Copyright (c) 2024 by bytedesk.com, All Rights Reserved. 
 */
// 
import Dexie, { Table, liveQuery } from "dexie";

export interface ThreadTable {
    id?: number;
    uid?: string;
    topic?: string;
    type?: string;
    status?: string;
    extra?: string;
    createdAt?: string;
    // 
    userUid?: string;
    userNickname?: string;
    userAvatar?: string;
    // 
    currentUid?: string;
  }
  
  export interface MessageTable {
    id?: number;
    uid?: string;
    type?: string;
    content?: string;
    client?: string;
    extra?: string;
    createdAt?: string;
    status?: string;
    // 
    threadTopic?: string;
    // 
    userUid?: string;
    userNickname?: string;
    userAvatar?: string;
    // 
    currentUid?: string;
  }
  
  // 创建一个Dexie数据库实例
  // const db = new Dexie("MessagesDB");
  // 定义数据库结构
  // db.version(1).stores({
  //   messages: "++id, content, timestamp",
  // });
  
  // CRUD操作
  export class MyIndexedDbService extends Dexie {
    // 'messages' is added by dexie when declaring the stores()
    // We just tell the typing system this is the case
    threads!: Table<ThreadTable>;
    messages!: Table<MessageTable>;
  
    constructor() {
      super("bytedesk-db-v1");
      this.version(1).stores({
        threads: "++id, uid", // Primary key and indexed props
        messages: "++id, uid", // Primary key and indexed props
      });
    }
  
    // 创建Message
    async createMessage(message: MESSAGE.MessageResponse) {
        console.log('useIndexedDB createMessage', message.content)
      return await db.messages.put({ 
            uid: message.uid,
            type: message.type,
            content: message.content,
            client: message.client,
            // extra: message.extra,
            createdAt: message.createdAt,
            status: "unread",
            threadTopic: message.threadTopic,
        });
    }
  
    // 读取所有Message
    async getAllMessages() {
      return await db.messages.toArray();
    }
  
    async getMessage(id: number) {
      return await db.messages.get(id);
      // return await db.friends.where("age").between(18, 65).toArray();
    }
  
    // 更新Message
    async updateMessage(id: number, content: string) {
      return await db.messages.update(id, { content });
    }
  
    // 删除Message
    async deleteMessage(id: number) {
      return await db.messages.delete(id);
    }
  
    private subscribeMessages() {
      // 监听 数据变化，更新 likeStore、playStore 中的数据
      const messagesObservable = liveQuery(() => this.messages.toArray());
      messagesObservable.subscribe({
        next: (value) => {
          const uids = value.map((item) => item.uid);
          console.log("messagesObservable message uids", uids);
          // myFavoriteStore.setState({ musicIds: ids });
        },
      });
    }
  }
  
  export const db = new MyIndexedDbService();
  